﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.MVC.DependencyInjection
{
	/// <summary>
	/// To enable Disposal inside of an MVC app this following line needs to be added to the HttpModule section
	/// add name="ContainerDisposal" type="StyleMVVM.MVC.DependencyInjection.ContainerDisposableHttpModule, StyleMVVM.MVC"
	/// </summary>
	public class ContainerDisposableHttpModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			context.BeginRequest += ContextOnBeginRequest;
			context.EndRequest += ContextOnEndRequest;
		}

		private void ContextOnBeginRequest(object sender, EventArgs eventArgs)
		{
			HttpContext.Current.Items["DisposalScope"] = new DisposalScope();
		}

		private void ContextOnEndRequest(object sender, EventArgs eventArgs)
		{
			DisposalScope disposalScope = HttpContext.Current.Items[DisposalScope.DisposalScopeStringKey] as DisposalScope;

			if (disposalScope != null)
			{
				disposalScope.Dispose();
			}
		}

		public void Dispose()
		{

		}
	}
}
